package com.txc.common.global.model;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.txc.common.config.mybatisplus.constant.DataScopeConstants;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Data;


import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import static com.txc.common.global.constant.NumConstant.ZERO;

/**
 * 用户信息
 *
 * @ClassName: UserInfo
 * @Author: TXC
 * @Date: 2023-08-08 16:56
 **/
@Data
public class LoginUser implements Serializable {
    /**
     * 主键
     */
    private Long id;

    /**
     * 用户名
     */
    @NotBlank(message = "用户名不能为空")
    private String username;

    /**
     * 昵称
     */
    @NotBlank(message = "昵称不能为空")
    private String nickname;

    /**
     * 头像地址
     */
    private String headUrl;

    /**
     * 邮箱
     */
    @Email(message = "邮箱格式错误")
    private String email;

    /**
     * 密码
     */
    @NotBlank(message = "密码不能为空")
    private String password;

    /**
     * 电话
     */
    @NotBlank(message = "电话不能为空")
    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "无效的手机号码格式")
    private String telephone;

    /**
     * 所属部门
     */
    private Long deptId;

    /**
     * 角色列表
     */
    private List<SysRole> roles = new ArrayList<>();

    private Map<String, UserPermission> permissions = new HashMap<>();

    public List<String> obtainPermissionsCodeList() {
        Set<String> permissionSet = new HashSet<>();
        permissions.forEach((key, value) -> {
            if (value.isHasPermission()) {
                permissionSet.add(value.getCode());
            }
        });
        return new ArrayList<>(permissionSet);
    }

    public Map<String, Boolean> obtainPermissionsMap() {
        Map<String, Boolean> permissionMap = new HashMap<>();
        permissions.forEach((key, value) -> {
            permissionMap.put(value.getCode(), value.isHasPermission());
        });
        return permissionMap;
    }


    public List<SysRole> obtainRolesByPermissionsCode(String permissionsCode) {
        List<SysRole> matchedRoles = new ArrayList<>();
        // 遍历所有角色
        for (SysRole role : roles) {
            // 检查permissions是否为null
            if (ObjectUtil.isNotNull(role.getPermissions())) {
                // 遍历每个角色的权限
                for (SysPermission permission : role.getPermissions()) {
                    // 检查权限编码是否匹配
                    if (StrUtil.isNotBlank(permission.getCode()) && permission.getCode().equals(permissionsCode)) {
                        matchedRoles.add(role);
                        break;
                    }
                }
            }
        }
        return matchedRoles;
    }

    public SysRole obtainRoleDataScope(List<SysRole> roles) {
        Map<String, List<SysRole>> roleMap = roles.stream().collect(Collectors.groupingBy(SysRole::getDataScope,
                Collectors.toList()));
        if (roleMap.containsKey(DataScopeConstants.DATA_SCOPE_ALL)) {
            return roleMap.get(DataScopeConstants.DATA_SCOPE_ALL).get(ZERO);
        } else if (roleMap.containsKey(DataScopeConstants.DATA_SCOPE_CUSTOM) || roleMap.containsKey(DataScopeConstants.DATA_SCOPE_DEPT) || roleMap.containsKey(DataScopeConstants.DATA_SCOPE_DEPT_AND_CHILD)) {
            List<SysRole> roleList = new ArrayList<>();
            roleList.addAll(roleMap.getOrDefault(DataScopeConstants.DATA_SCOPE_CUSTOM, new ArrayList<>()));
            roleList.addAll(roleMap.getOrDefault(DataScopeConstants.DATA_SCOPE_DEPT, new ArrayList<>()));
            roleList.addAll(roleMap.getOrDefault(DataScopeConstants.DATA_SCOPE_DEPT_AND_CHILD, new ArrayList<>()));
            Set<Long> deptIdList = new HashSet<>();
            roleList.forEach(role -> {
                if (ObjectUtil.isNotNull(role.getDeptIds())) {
                    deptIdList.addAll(role.getDeptIds());
                }
            });
            SysRole role = roleList.get(ZERO);
            role.setDeptIds(new ArrayList<>(deptIdList));
            return role;
        } else {
            if (ObjectUtil.isNotEmpty(roles)) {
                return roleMap.get(DataScopeConstants.DATA_SCOPE_SELF).get(ZERO);
            }
            return null;
        }
    }
}
